// Modules to control application life and create native browser window
const fs = require("fs");
const coordtransform = require("./coordtransform.js");
const { app, BrowserWindow, ipcMain, Menu, dialog } = require("electron");
const path = require("path");
const xlsx = require("xlsx");

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      nodeIntegration: true,
    },
  });
  Menu.setApplicationMenu(null);
  // and load the index.html of the app.
  mainWindow.loadFile("index.html");

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
}

ipcMain.on("search-path", (event, arg) => {
  console.log(arg);
  const start = coordtransform.gcj02towgs84(
    arg.start.location.lng,
    arg.start.location.lat
  );
  let content = `${start[0].toFixed(12)} ${start[1].toFixed(12)}\r\n`;
  arg.routes[0].steps.forEach((element) => {
    element.path.forEach((path) => {
      const info = coordtransform.gcj02towgs84(path.lng, path.lat);
      content += `${info[0].toFixed(12)} ${info[1].toFixed(12)}\r\n`;
    });
  });
  const end = coordtransform.gcj02towgs84(
    arg.end.location.lng,
    arg.end.location.lat
  );
  content += `${end[0].toFixed(12)} ${end[1].toFixed(12)}`;
  fs.writeFile(
    `./paths/${start[0].toFixed(12)},${start[1].toFixed(12)}-${end[0].toFixed(
      12
    )},${end[1].toFixed(12)}.txt`,
    content,
    (err) => {
      if (err) {
        console.error(err);
        return;
      }
      //文件写入成功。
    }
  );
});

ipcMain.on("open-file", async (event, arg) => {
  const result = await dialog.showOpenDialog({ properties: ["openFile"] });
  let workbook = xlsx.readFile(result.filePaths[0]);
  let sheetNames = workbook.SheetNames; //获取表明
  let sheet = workbook.Sheets[sheetNames[0]]; //通过表明得到表对象
  var data = xlsx.utils.sheet_to_json(sheet); //通过工具将表对象的数据读出来并转成json
  event.sender.send('xlsx-select',data);
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow();

  app.on("activate", function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
  if (process.platform !== "darwin") app.quit();
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
